package com.cy.pj.sys.service.impl;

import com.cy.pj.common.pojo.PageObject;
import com.cy.pj.sys.dao.SysTypeDao;
import com.cy.pj.sys.pojo.SysGoods;
import com.cy.pj.sys.pojo.SysGoodsType;
import com.cy.pj.sys.service.SysTypeService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class SysTypeServiceImpl implements SysTypeService {

    @Autowired
    private SysTypeDao sysTypeDao;

    @Override
    public PageObject<SysGoodsType> findPageObjects(String typeName, Integer pageCurrent) {
        System.out.println("SysGoodsServiceImpl.findPageObjects.thread->" + Thread.currentThread().getName());
        //1.参数校验
        if (pageCurrent == null || pageCurrent < 1)
            throw new IllegalArgumentException("页码值不正确");
        //2.查询当前页记录
        //使用PageHelper最关键的一个步骤,这里表示启动PageHelper的内置拦截器,拦截查询请求,然后对SQL做处理.
        Page<SysGoodsType> page = PageHelper.startPage(pageCurrent, 10);//这里的3为pagesize

        System.out.println(typeName);

        List<SysGoodsType> records = sysTypeDao.doFindType(typeName);
        //4.封装查询结果并返回
        return new PageObject<>(page.getTotal(), records, Long.valueOf(page.getPages()), 3, pageCurrent.longValue());

    }

    @Override
    public int insertObject(String typeName) {
        if (StringUtils.isEmpty(typeName))
            throw new RuntimeException("请输入分类名称");

        SysGoodsType obj = sysTypeDao.selectByName(typeName);
        if ((!StringUtils.isEmpty(obj)) && obj.getTypeName().equals(typeName))
            throw new RuntimeException("类名已存在");

        return sysTypeDao.insertObject(typeName);
    }

    @Override
    public SysGoodsType findObjectById(Integer id) {
        System.out.println(id);
        SysGoodsType object = sysTypeDao.findObjectById(id);
        System.out.println(object);
        return object;
    }

    @Override
    public void updateObject(SysGoodsType sysGoodsType) {
        String typeName = sysGoodsType.getTypeName();

        System.out.println(typeName);

        if (StringUtils.isEmpty(typeName))
            throw new RuntimeException("输入的分类名不能为空");

        SysGoodsType obj = sysTypeDao.selectByName(typeName);
        System.out.println(obj);
        if (StringUtils.isEmpty(obj))
            sysTypeDao.updateObject(sysGoodsType);
        else if (obj.getTypeName().equals(typeName) && !(obj.getId().equals(sysGoodsType.getId())))
            throw new RuntimeException("此分类已存在");
    }

}
